<template>
  <!--印章授权审核申请单-->
  <a-spin :spinning="confirmLoading" style="background: #fff">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <!-- <a-col :span="8">
            <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
              <a-input placeholder="请输入标题" :disabled="formDisabled" v-model="model.bpmBizTitle"></a-input>
            </a-form-model-item>
          </a-col> -->
          <a-col :span="8">
            <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="handlerId">
              <!--              <select-person-input-->
              <!--                  :disabled=formDisabled-->
              <!--                  v-model="model.handlerId" disabled/>-->
              <select-user-by-dep :multi="false" v-model="model.handlerId" disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="handlerDeptId">
              <j-select-depart v-model="model.handlerDeptId" disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
              <j-date
                placeholder="请选择申请时间"
                v-model="model.createTime"
                :show-time="true"
                date-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
                disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyCode">
              <a-input v-model="model.applyCode" placeholder="请输入单据编号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="印章所属公司" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sealCompany">
              <select-Company-input :disabled="formDisabled" v-model="model.sealCompany" @change="handleSealChange"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="选择印章" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ids">
              <a-tooltip placement="topLeft">
                <template slot="title" v-if="!model.sealCompany">
                  <span>请选择印章所属公司</span>
                </template>
                <select-normal-seal-input
                  ref="sealInput"
                  :company="model.sealCompany"
                  :disabled="formDisabled ? formDisabled : !model.sealCompany"
                  v-model="model.ids"/>
              </a-tooltip>
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item label="申请授权公司" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyCompany">
              <!--              <j-select-depart :disabled=formDisabled type="list" v-model="model.applyCompany" dictCode=""-->
              <!--                               placeholder="请选择申请授权公司"/>-->
              <select-Company-input :disabled="formDisabled" v-model="model.applyCompany" @back="backCompany"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请授权部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyDept">
              <j-select-depart
                :disabled="formDisabled"
                type="list"
                v-model="model.applyDept"
                dictCode=""
                placeholder="请选择申请授权部门"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请授权责任人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyAuthPerson">
              <!--              <select-person-input-->
              <!--                  :disabled=formDisabled-->
              <!--                  v-model="model.applyAuthPerson"/>-->
              <select-user-by-dep :disabled="formDisabled" :multi="false" v-model="model.applyAuthPerson" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="被委托方（印章保管人）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="trustee">
              <!--              <select-person-input-->
              <!--                  :disabled=formDisabled-->
              <!--                  v-model="model.trustee"/>-->
              <select-user-by-dep :disabled="formDisabled" :multi="false" v-model="model.trustee" />
            </a-form-model-item>
          </a-col>

          <a-col :span="16">
            <a-form-model-item label="授权印章使用期限" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="authDateStart">
              <a-date-picker
                :disabled="formDisabled"
                placeholder="请选择授权印章开始时间"
                @change="handleChange"
                v-model="model.authDateStart"
                date-format="YYYY-MM-DD HH:mm"
                style="width: 48%" />
              <span class="fontDiy" style="width: 4px">~</span>
              <a-date-picker
                :disabled="formDisabled"
                :disabled-date="disabledDate"
                :default-picker-value="this.model.authDateStart"
                placeholder="请选择授权印章结束时间"
                v-model="model.authDateEnd"
                date-format="YYYY-MM-DD HH:mm"
                style="width: 48%" />
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectName">
              <a-input
                v-if="formDisabled"
                readOnly
                @click.prevent="onDetail(model.projectName)"
                v-model="model.projectName_dictText"
                style="color: #1890FF; cursor: pointer;"
                placeholder="请选择项目名称"></a-input>
              <select-project-input v-else :disabled="formDisabled" v-model="model.projectName" placeholder="请选择项目名称">
              </select-project-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="授权范围及授权说明" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="scopeContent">
              <a-textarea
                :rows="4"
                :disabled="formDisabled"
                v-model="model.scopeContent"
                :max-length="500"
                placeholder="请输入授权范围及授权说明"></a-textarea>
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="上传附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="upload">
              <j-upload :disabled="formDisabled" v-model="model.upload"></j-upload>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
    </j-form-container>
    <a-row :gutter="48" v-if="formBpm">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button @click="onPrint" type="primary">打印</a-button>
      </a-col>
    </a-row>
    <!-- 项目详情开始 -->
    <erp-project-report-modal ref="prejectForm"></erp-project-report-modal>
    <!-- 项目详情结束 -->

    <erp-seal-qualification-authorization-audit-form-print v-if="formBpm" id="sealauthorizationContent" class="print_style" :formData1="model" :formDataHistory="formData"></erp-seal-qualification-authorization-audit-form-print>
  </a-spin>
</template>

<script>

import { getAction, httpAction } from '@/api/manage';
import SelectNormalSealInput from './SelectNormalSealInput';
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
import moment from 'moment';
import { mapGetters } from 'vuex';
import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
import JEllipsis from '@/components/jeecg/JEllipsis'
import CommonFlowList from '@/views/components/CommonFlowList.vue';
import ErpProjectReportModal from '@/views/erp/report/project/modules/ErpProjectReportModal'
import Print from '@/utils/print/printarea.js';
import ErpSealQualificationAuthorizationAuditFormPrint from './ErpSealQualificationAuthorizationAuditFormPrint' // 打印组件
export default {
  name: 'ErpSealAuthorizationInformationForm',
  components: {
    SelectNormalSealInput,
    SelectUserByDep,
    SelectProjectInput,
    SelectCompanyInput,
    JEllipsis,
    CommonFlowList,
    ErpProjectReportModal,
    ErpSealQualificationAuthorizationAuditFormPrint
  },
  props: {
    // 流程表单data
    formData: {
      type: Object,
      default: () => {},
      required: false
    },
    // 表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      model: {},
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
      confirmLoading: false,
      validatorRules: {
        // bpmBizTitle:[
        //   { required: true, message: '请输入标题!' }
        // ],
        sealCompany: [{ required: true, message: '请选择印章所属公司!' }],
        applyCompany: [{ required: true, message: '请选择申请授权公司!' }],
        applyDept: [{ required: true, message: '请选择申请授权部门!' }],
        applyAuthPerson: [{ required: true, message: '请选择申请授权责任人!' }],
        trustee: [{ required: true, message: '请选择被委托方（印章保管人）!' }],
        authDateStart: [{ required: true, message: '请选择授权印章使用期限!' }],
        scopeContent: [{ required: true, message: '请输入授权范围及授权说明!' }],
        ids: [
          { required: true, message: '请选择印章!' }
        ]
      },
      url: {
        add: '/api/erp/administration/seal/erpSealQualificationAuthorizationAudit/add',
        edit: '/api/erp/administration/seal/erpSealAuthorizationInformation/edit',
        queryById: '/api/erp/administration/seal/erpSealAuthorizationInformation/queryById',
        newUrl: '/api/erp/administration/seal/erpSealAuthorizationInformation/queryByIdNew',
        queryByIds: '/api/erp/administration/seal/erpSealQualificationAuthorizationAudit/queryById',
        generatedFormNumber: '/api/erp/base/generatedFormNumber',
        queryProjectReportById: '/api/erp/project/report/erpProjectReport/queryById'
      },
      sealDisabled: false
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }
  },
  created() {
    // 备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
    // 如果是流程中表单，则需要加载流程表单data
    this.showFlowData();
  },
  methods: {
    // 生成单号，反写到编号和标题
    generatedFormNumber() {
      getAction(this.url.generatedFormNumber, { prefix: 'YZSQ', subSystemCode: '04' }).then(res => {
        if (res.success) {
           // 单据编号
            this.$set(this.model, 'applyCode', res.result)
            // 标题 申请人-单据编号
            this.$set(this.model, 'bpmBizTitle', this.userInfo().empName + '-' + res.result)
        }
      })
    },
    ...mapGetters(['userInfo']),
    handleChange(value) {
      if (this.model.insuranceEndTime) {
        if ((this.model.insuranceEndTime).diff((this.model.insuranceStartTime), 'days') < 0) {
          this.model.insuranceEndTime = this.model.insuranceStartTime
        }
      }
    },
    disabledDate(current) {
      return current < moment(this.model.authDateStart).subtract('day')
    },
    add() {
      this.edit(this.modelDefault);
      this.model.handlerId = this.userInfo().empId;
      this.model.handlerDeptId = this.userInfo().deptId;
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm');
      this.generatedFormNumber();
      this.sealDisabled = false;
    },
    edit(record) {
      this.$refs.form.resetFields();
      this.model = Object.assign({}, record);
      this.visible = true;
      // 根据ID查询
      getAction(this.url.queryById, { id: record.id }).then((res) => {
        if (res.success) {
          // const model = res.result
          // this.$refs.realForm.edit(model);
          this.model = res.result
          this.$set(this.model, 'companyLevel', record.companyLevel || '')
          // this.model.ids = record.baseId
        }
      })
      // if (record.mainId) {
      //   this.model.ids = record.mainId
      // }
    },
    // 渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId };
        getAction(this.url.queryByIds, params).then((res) => {
          if (res.success) {
            this.edit(res.result);
          }
        });
      }
    },
    submitForm(type) {
      const that = this;
      if (type == 'draft') {
        // 代表保存草稿不做校验
        this.submit(type)
      } else if (type == 'submit') {
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.submit(type)
          } else {
            that.$emit('unButtonDisable')
          }
        })
      } else {
        console.log('传参数，保存：draft，提交：submit')
      }
    },
    submit (type) {
      const that = this;
      that.confirmLoading = true;
      let httpurl = '';
      let method = '';
      if (!this.model.id) {
        httpurl += this.url.add;
        method = 'post';
      } else {
        httpurl += this.url.edit;
        method = 'put';
      }
      httpAction(httpurl, this.model, method).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          if (method == 'post') {
            that.model.id = res.result;
          } else {
            that.model.id = that.model.mainId;
          }
          that.$emit('ok', type, that.model);
        } else {
          that.$message.warning(res.message);
          that.$emit('unButtonDisable');
        }
      }).catch((error) => {
        that.$emit('unButtonDisable', error);
      }).finally(() => {
        that.confirmLoading = false;
      })
    },

    // 穿透项目底表
    onDetail(id) {
      const that = this
      this.$nextTick(() => {
        getAction(this.url.queryProjectReportById, { id }).then((res) => {
          if (res.success) {
            const model = res.result
            that.$refs.prejectForm.getDetail(model);
            that.$refs.prejectForm.title = '项目一览表';
          }
        })
      })
    },
    /*
        印章所属公司改变清空印章列表
         */
    handleSealChange() {
      this.$refs.sealInput.resetObj()
      this.$delete(this.model, 'ids')
    },
    backCompany(val) {
      if (val.length) {
        const data = val[0]
        this.$set(this.model, 'companyLevel', data.companyLevel)
      }
    },
    // 点击打印
    onPrint () {
      let print = new Print({
        el: '#sealauthorizationContent',
        popTitle: '印章授权审核详情 · 禾美环保',
        endCallback() {

        }
      })
    }
  }
}
</script>
<style>
  @import "../../../../../utils/print.css";
  .print_style{
  position: absolute;
  top: 0;
  z-index: -1111;
}
</style>
